package com.dgut.lab.controller;

import com.alibaba.excel.EasyExcel;
import com.dgut.lab.entity.User;
import com.dgut.lab.security.SecurityUserDetails;
import com.dgut.lab.service.UserService;
import com.dgut.lab.util.CommonUtil;
import com.dgut.lab.util.ParamUtil;
import com.dgut.lab.util.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户登录",tags = {"用户管理"})
    @GetMapping("/success")
    public SecurityUserDetails success(){
        return (SecurityUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    @ApiOperation(value = "用户添加",tags = {"用户管理"})
    @ResponseBody
    @PostMapping("/user/add")
    public Object addUser(@RequestBody User user){
        User addUser = userService.addUser(user);
        if(addUser !=null){
            return ResponseUtil.ok(addUser);
        }
        return ResponseUtil.fail(1,"用户添加失败！");
    }

//    @ApiOperation(value = "用户禁用",tags = {"用户管理"})
//    @DeleteMapping("/user/delete/{username}")
//    public Object deleteUser(@PathVariable("username") String username){
//        User user = new User();
//        user.setUsername(username);
//        user.setEnabled(0);
//        boolean b = userService.modifyUserStatus(user);
//        if(b){
//            return ResponseUtil.ok();
//        }
//        else return ResponseUtil.fail(2,"禁用失败");
//    }

    @ApiOperation(value = "用户基础信息修改",tags = {"用户管理"})
   @PutMapping("/user/update")
    public Object updateUser(@RequestBody User user){
       boolean b = userService.modifyUserBasic(user);
       if(b){
           return ResponseUtil.ok();
       }
       else return ResponseUtil.fail(3,"修改失败！");
   }

   @GetMapping("/user/modifyEnabled/{username}/{enabled}")
   public Object modifyUserEnabled(@PathVariable("username") String username,
                                   @PathVariable("enabled") Integer enabled){
       User user = new User();
       user.setUsername(username);
       user.setEnabled(enabled);
       boolean b = userService.modifyUserStatus(user);
       if(b){
           Map<String, Object> map = new HashMap<>();
           map.put("enabled",enabled==1?0:1);
           map.put("str",enabled==1?"锁定":"解锁");
           return ResponseUtil.ok(map);

       }
       else return ResponseUtil.fail(3,"修改失败！");
   }

//    @ApiOperation(value = "分页获取用户",tags = {"用户管理"})
//    @PreAuthorize(value = "hasRole('ROLE_ADMIN')")
//    @GetMapping("/user/{page}/{rows}")
//    public Object getUsers(@PathVariable("page") Integer page,
//                           @PathVariable("rows") Integer rows){
//        Page<User> users = userService.queryAllByPage(page, rows);
//        if(users!=null){
//            return ResponseUtil.ok(users);
//        }
//        return ResponseUtil.fail(4,"分页查询失败！");
//    }

    @PreAuthorize(value = "hasRole('ROLE_ADMIN')")
    @GetMapping("/user/allUsers")
    public Object allUsers(){
        List<User> users = userService.queryAllUsers();
        if(users.size()>0)
            return ResponseUtil.ok(CommonUtil.userListToListMap(users,true));
        else
            return ResponseUtil.fail(-1,"没有查询结果");
    }

    @ApiOperation(value = "用户信息获取",tags = {"用户管理"})
    @PreAuthorize(value = "hasRole('ROLE_STUDENT') or hasRole('ROLE_ADMIN')")
    @GetMapping("/user/{username}")
    public Object getUser(@PathVariable("username") String username){
        User user = userService.queryByUsername(username);
        if(user!=null){
            user.setPassword(null);
            user.setEnabled(null);
            return ResponseUtil.ok(user);
        }
        return ResponseUtil.fail(4,"查询失败");
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/user/unSignExcelDownload")
    public void down(HttpServletRequest request, HttpServletResponse response,
                     @Param("username") String username,
                     @Param("department") String department,
                     @Param("name") String name,
                     @Param("major") String major
                     ) throws IOException, ParseException {
        Map<String,Object> map = new HashMap<>();
        map.put("username", ParamUtil.parmeterNormal(username));
        map.put("department",ParamUtil.parmeterNormal(department));
        map.put("name",ParamUtil.parmeterNormal(name));
        map.put("major",ParamUtil.parmeterNormal(major));

        List<User> users = userService.queryUnSign(map);
        cooperation(request,response,users);
    }

    @Async   //下载文件，肯定多线程
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) //异常
    public void cooperation(HttpServletRequest request, HttpServletResponse response,List<User> users) throws IOException {
        response.setContentType("application/vnd.ms-excel");  // excel 的响应头
        response.setCharacterEncoding("utf-8");
        // 文件名字
        String fileName = URLEncoder.encode(System.currentTimeMillis()+"", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<User> resp = users;
        EasyExcel.write(response.getOutputStream(), User.class).sheet("模板").doWrite(resp);
    }

//    @GetMapping("/user/condition/{page}/{rows}")
//    public Object queryByCondition(@RequestBody Map<String,Object> map,
//                                   @PathVariable(value = "page",required = false) Integer page,
//                                   @PathVariable(value = "rows",required = false) Integer rows) throws ParseException {
//        page = page <= 0 ?page:1;
//        rows = rows <= 0  ?rows:10;
//        return ResponseUtil.ok(userService.queryUserByCondition(map,page,rows));
//    }

//    @GetMapping("/user/queryTest")
//    public Object queryTest(@RequestBody Map<String, Object>map){
//        List<User> users = userService.queryUser(map);
//        return ResponseUtil.ok(users);
//    }

    @PostMapping("/user/queryUnSign")
    public Object queryUnSign(@RequestBody  HashMap<String, Object> map) throws ParseException {
        List<Map<String, Object>> mapList = CommonUtil.userListToListMap(userService.queryUnSign(map),false);
        if(mapList!=null)
            return ResponseUtil.ok(mapList);
        else
            return ResponseUtil.fail(-1,"根据条件未查询到结果");
    }
}
